package common

import (
	"gitee.com/yaodae/server-lib-go/component/redis"
	"gitee.com/yaodae/server-lib-go/utils"
	"time"
)

var lockName = "locks:"
var lockExpire = 2
var unlockScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"

func RedisLock(res string, goId uint64) {
	key := lockName + res
	value := utils.Uint64ToStr(goId)
	checkValue := redis.RGet(key)
	if value == checkValue {
		return
	}
	for true {
		if redis.RSetNxAndEx(key, value, lockExpire) {
			break
		}
		time.Sleep(time.Duration(1) * time.Millisecond)
	}
}

func RedisGetLock(res string, goId uint64) bool {
	key := lockName + res
	value := utils.Uint64ToStr(goId)
	checkValue := redis.RGet(key)
	if value == checkValue {
		return true
	}
	return redis.RSetNxAndEx(key, value, lockExpire)
}

func RedisUnlock(res string, goId uint64) {
	key := lockName + res
	value := utils.Uint64ToStr(goId)
	checkValue := redis.RGet(key)
	if value == checkValue {
		keyList := make([]string, 0)
		keyList = append(keyList, key)
		_, _ = redis.REval(unlockScript, keyList, value)
	}
}
